<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/11/13 14:47
 * @copyright PanxSoft Inc.
 */

namespace App\Http\Controllers\Common;


use App\Exceptions\ApiErrCode;
use App\Http\Controllers\ApiController;

use App\Http\Requests\Common\SmsProxyRequest;
use App\Services\EasySms\EasySmsService;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;


class SendPhoneVerifyCodeController extends ApiController
{

    const MINUTES = 5;
    const DEFAULT_COUNTRY_CODE = 86; // 默认国家区号

    const ROUTES = [
        'smsProxy' => 'api.common.SendPhoneVerifyCode.smsProxy'
    ];

    private $easySmsService;

    public function __construct(EasySmsService $easySmsService)
    {
        $this->easySmsService = $easySmsService;
    }

    /**
     * @param SmsProxyRequest $request
     *
     * @return array
     * @throws \Exception
     */
    public function smsProxy(SmsProxyRequest $request)
    {
        try {
            return $this->easySmsService->send(
                $request->sign, $request->to, json_decode($request->message, true)
            );
        } catch (NoGatewayAvailableException $exception) {
            $exception = $exception->getException('aliyun');

            $this->checkFailed(trans('service.sms_failed_to_send', [
                'tip' => $exception->getMessage()
            ]), ApiErrCode::SMS_SEND_FAILED);
        } catch (\Exception $exception) {
            $this->checkFailed($exception->getMessage(), ApiErrCode::SMS_SEND_FAILED);
        }
    }
}